from sqlalchemy import func, insert, select, update
from forward.api.admin.schemas.merchant import (
    MerchantAddInSchema,
    MerchantDeleteInSchema,
    MerchantDetailInSchema,
    MerchantEditInSchema,
    MerchantListInSchema,
    MerchantOutSchema,
)
from forward.api.admin.schemas.system import SystemAuthAdminOutSchema
from forward.extend.pydantic.result_api import ResultAPI
from forward.model.tables.activity import ActivityModel
from forward.model.tables.merchant import MerchantModel
from forward.dependencies.database import db
from forward.model.tables.system import SystemAuthAdminModel


class MerchantService:
    @classmethod
    def instance(cls):
        return MerchantService()

    async def lists(self, list_in: MerchantListInSchema):
        where = []
        where.append(MerchantModel.is_deleted == 0)
        if list_in.name:
            where.append(MerchantModel.name.like(f"%{list_in.name}%"))
        if list_in.salesman_id:
            where.append(MerchantModel.salesman_id == list_in.salesman_id)
        if list_in.status is not None:
            where.append(MerchantModel.status == list_in.status)
        statement = (
            select(MerchantModel)
            .where(*where)
            .order_by(MerchantModel.id.desc())
            .limit(list_in.page_size)
            .offset((list_in.page_num - 1) * list_in.page_num)
        )
        records = await db.fetch_all(statement)

        statement_count = select(func.count(MerchantModel.id)).where(*where)
        count = await db.fetch_val(statement_count)
        merchants = [
            MerchantOutSchema.model_validate(record, from_attributes=True)
            for record in records
        ]
        for merchant in merchants:
            # 查询销售人员
            if merchant.salesman_id:
                statment = select(SystemAuthAdminModel).where(
                    SystemAuthAdminModel.id == merchant.salesman_id
                )
                record = await db.fetch_one(statment)
                salesman = SystemAuthAdminOutSchema.model_validate(
                    record, from_attributes=True
                )
                merchant.salesman = salesman.nickname if salesman else ""
            # 查询商家活动数量
            statement = (
                select(func.count())
                .select_from(ActivityModel)
                .where(ActivityModel.merchant_id == merchant.id)
            )
            record = await db.fetch_val(statement)
            merchant.activity_count = record
        return ResultAPI(
            data={
                "lists": merchants,
                "count": count,
            }
        )

    async def add(self, add_in: MerchantAddInSchema):
        statement = insert(MerchantModel).values(add_in.model_dump())
        await db.execute(statement)
        return ResultAPI()

    async def edit(self, edit_in: MerchantEditInSchema):
        statement = (
            update(MerchantModel)
            .where(MerchantModel.id == edit_in.id)
            .values(edit_in.model_dump())
        )
        await db.execute(statement)
        return ResultAPI()

    async def detail(self, detail_in: MerchantDetailInSchema):
        statement = select(MerchantModel).where(MerchantModel.id == detail_in.id)
        record = await db.fetch_one(statement)
        return ResultAPI(
            data=MerchantOutSchema.model_validate(record, from_attributes=True)
        )

    async def delete(self, delete_in: MerchantDeleteInSchema):
        # stetement = delete(MerchantModel).where(
        #     MerchantModel.id == delete_in.id)
        # await db.execute(stetement)
        # return ResultAPI()
        statement = (
            update(MerchantModel)
            .where(MerchantModel.id == delete_in.id)
            .values(is_deleted=1)
        )
        await db.execute(statement)
        return ResultAPI()
